package com.zdsoft.site.mina.state;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.statemachine.annotation.IoHandlerTransition;
import org.apache.mina.statemachine.annotation.State;
import org.apache.mina.statemachine.context.AbstractStateContext;
import org.apache.mina.statemachine.context.StateContext;
import org.apache.mina.statemachine.event.Event;
import org.apache.mina.statemachine.event.IoHandlerEvents;

public class PlayGameHandler extends IoHandlerAdapter {
	@State
	public static final String ROOT = "root";
	@State(ROOT)
	public static final String EMPTY = "empty";
	@State(ROOT)
	public static final String START = "start";
	@State(ROOT)
	public static final String PLAYING = "playing";
	@State(ROOT)
	public static final String STOP = "stop";

	@IoHandlerTransition(on = IoHandlerEvents.SESSION_OPENED, in = EMPTY)
	public void connect(IoSession session) {
		session.write(" Greetings you for playing games!");
	}

	@IoHandlerTransition(on = IoHandlerEvents.MESSAGE_RECEIVED, in = EMPTY, next = START)
	public void StartPlay(Event event, IoSession session, StartCommand cmd) {
		String tmp = "start the game!";
		// context.name="client";
		System.out.println("event:" + event);
		StateContext sc = event.getContext();
		System.out.println("stateContext" + sc);
		System.out.println(tmp + cmd.getName());
		session.write(tmp + cmd.getName());
	}

	@IoHandlerTransition(on = IoHandlerEvents.MESSAGE_RECEIVED, in = START, next = PLAYING)
	public void playing(Event event, IoSession session, PlayCommand cmd) {
		String tmp = " playing the game";
		System.out.println("event Object:" + event);
		StateContext sc = event.getContext();
		System.out.println("stateContext" + sc);
		Object[] hello = event.getArguments();
		for (int i = 0; i < hello.length; i++) {
			System.out.println(hello[i]);
		}
		System.out.println(tmp);
		System.out.println("eventId:" + event.getId());
		session.write(tmp + "eventId:" + event.getId());

	}

	@IoHandlerTransition(on = IoHandlerEvents.MESSAGE_RECEIVED, in = PLAYING, next = STOP)
	public void stopGame(IoSession session, StopCommand sc) {
		String tmp = " Game Over!";
		System.out.println(tmp);
		session.write(tmp);
	}

	@IoHandlerTransition(on = IoHandlerEvents.EXCEPTION_CAUGHT, in = ROOT)
	public void commandSyntaxError(IoSession session, Exception e) {
		session.write(e.getMessage());
	}

	@IoHandlerTransition(on = IoHandlerEvents.EXCEPTION_CAUGHT, in = ROOT, weight = 10)
	public void exceptionCaught(IoSession session, Exception e) {
		e.printStackTrace();
		session.close(true);
	}

	@IoHandlerTransition(in = ROOT, weight = 10)
	public void unhandledEvent() {
	}

	static class GameContext extends AbstractStateContext {
		public String name;
	}
}
